package com.example.demo.common.vo;/**
 * Created by penglee on 2019/7/3.
 */

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * EntityUtils
 * <p>
 * Description: <br>
 * Created in 2019/7/3 08:32 <br>
 *
 * @author 李鹏
 */
public class EntityUtils {

    /**
     * Description: entityToMap 实体类转Map
     * Params: [object]
     * Return: java.util.Map<java.lang.String,java.lang.Object>
     * CreateDate: Created in  2019/8/8 17:49
     * Modify:
     * Author: 李鹏
     */
    public static Map<String, Object> entityToMap(Object object) {
        Map<String, Object> map = new HashMap();
        for (Field field : object.getClass().getDeclaredFields()) {
            try {
                boolean flag = field.isAccessible();
                field.setAccessible(true);
                Object o = field.get(object);
                map.put(field.getName(), o);
                field.setAccessible(flag);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    /**
     * Description: mapToEntity Map转实体类。需要初始化的数据，key字段必须与实体类的成员名字一样，否则赋值为空
     * Params: [map, entity]
     * Return: T
     * CreateDate: Created in 2019/8/8 17:49
     * Modify:
     * Author: 李鹏
     */
    public static <T> T mapToEntity(Map<String, Object> map, Class<T> entity) {
        T t = null;
        try {
            t = entity.newInstance();
            for (Field field : entity.getDeclaredFields()) {
                if (map.containsKey(field.getName())) {
                    boolean flag = field.isAccessible();
                    field.setAccessible(true);
                    Object object = map.get(field.getName());
                    if (object != null && field.getType().isAssignableFrom(object.getClass())) {
                        field.set(t, object);
                    }
                    field.setAccessible(flag);
                }
            }
            return t;
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return t;
    }
}
